package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.UserService;
import com.lagou.edu.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private AuthDao authDao;

    @Override
    public User findByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        Example<User> example = Example.of(user);
        Optional<User> opt = userDao.findOne(example);
        if (opt != null && opt.isPresent()) {
            return opt.get();
        }
        return null;
    }

    @Transactional(readOnly = true)
    @Override
    public User findByToken(String token) {
        User user = new User();
        user.setToken(token);
        Example<User> example = Example.of(user);
        Optional<User> opt = userDao.findOne(example);
        if (opt != null && opt.isPresent()) {
            return opt.get();
        }
        return null;
    }

    @Override
    public Boolean register(String email, String password, String code) {
        // 获取token
        String token = MD5Utils.encrypt(email, password);

        // 保存令牌
        User user = new User();
        user.setEmail(email);
        user.setToken(token);
        userDao.save(user);

        return true;
    }

    @Override
    public String login(String email, String password) {
        // 获取token
        String token = MD5Utils.encrypt(email, password);

        User user = findByToken(token);
        if (user == null) {
            return null;
        }
        return user.getEmail();
    }

}
